package stardust.product.platform.webc.support;


import java.util.LinkedList;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


public class ServletMonitor implements HttpSessionListener, ServletContextListener
{
  
  public static final String SESSION_MONITOR_ATTRIBUTE = "SESSION_MONITOR";
  
  private LinkedList<HttpSession> session = new LinkedList<HttpSession>();
  
  public synchronized HttpSession get(String sessionId)
  {
    for (HttpSession s : this.session)
    {
      if (s.getId().equals(sessionId))
      {
        return s;
      }
    }
    
    return null;
  }

  public synchronized void sessionCreated(HttpSessionEvent sessionEvent)
  {
    this.session.add(sessionEvent.getSession());
  }

  public synchronized void sessionDestroyed(HttpSessionEvent sessionEvent)
  {
    this.session.remove(sessionEvent.getSession());
  }
  
  public void contextInitialized(ServletContextEvent contextEvent)
  {
    contextEvent.getServletContext().setAttribute(ServletMonitor.SESSION_MONITOR_ATTRIBUTE, this);
  }

  public void contextDestroyed(ServletContextEvent contextEvent)
  {
    contextEvent.getServletContext().removeAttribute(ServletMonitor.SESSION_MONITOR_ATTRIBUTE);
  }
  
  public static ServletMonitor getServletMonitor(ServletContext context)
  {
    return (ServletMonitor) context.getAttribute(ServletMonitor.SESSION_MONITOR_ATTRIBUTE);
  }

}
